package com.example.demo6;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
        private TextView text,t_text;  //显示信息
        private List<message> list; //创建实体信息集合
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化组件
        text=findViewById(R.id.text);
        t_text=findViewById(R.id.t_text);
        list=new ArrayList<message>();
    }
    /**
     * 点击按钮时，先获取权限在获取短信
     */
    public void show(View view) {
        //获取动态权限
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_SMS},1);
    }

    /**
     * 申请系统权限
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //判断编码是否一致
        if(requestCode==1)
        {
            for (int i=0;i<permissions.length;i++)
            {
                //检查是否权限
                if(grantResults[i]==PackageManager.PERMISSION_GRANTED)
                {
                    //获取短信信息
                    getsms();
                }else
                {
                    Toast.makeText(this, "权限"+permissions[i]+"申请失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 获取短信的信息
     */
    private void getsms() {
        //获取系统信息的uri
        Uri uri = Uri.parse("content://sms/");
        //创建ContentResolver对象，操作系统系统
        ContentResolver contentResolver=getContentResolver();
        //通过ContentResolver对象，查询系统短信
        Cursor cursor = contentResolver.query(uri, new String[]{"_id", "address", "body"}, null, null, null);
        if (cursor!=null&&cursor.getCount()>0)
        {
            t_text.setText("读取到的系统短信信息如下：");
            if (list!=null)
            {
                list.clear();
            }
            //拼凑内容
            String str="";
            //移动指针直到结束
            while (cursor.moveToNext())
            {
                str+="\n";
                str+="手机号码："+cursor.getString(1)+"\n";
                str+="短信内容："+cursor.getString(2)+"\n";
            }
            text.setText(str);
            cursor.close();
        }
    }
}